﻿#define _CRT_SECURE_NO_WARNINGS 1

//模拟实现qsort库函数

//个人博客：https://blog.csdn.net/T_L_the_language?type=blog

#include <stdio.h>

void Swap(char* buf1, char* buf2, size_t size)
{
	int i = 0;
	for (i = 0; i < size; i++)
	{
		char tmp = *buf1;
		*buf1 = *buf2;
		*buf2 = tmp;
		buf1++;
		buf2++;
	}
}

void bubble_sort(void* base, size_t num, size_t size, int cmp(const void*, const void*))
{
	int i = 0;
	int j = 0;
	for (i = 0; i < num - 1; i++)
	{
		int flag = 0;
		for (j = 0; j < num - 1 - i; j++)
		{
			if (cmp((char*)base + j * size, (char*)base + (j + 1) * size) > 0)
			{
				Swap((char*)base + j * size, (char*)base + (j + 1) * size, size);
			}
		}
	}
}
//下面实验一下bubble_sort

//整型的比较
int cmp_int(const void* buf1, const void* buf2)
{
	return *(int*)buf1 - *(int*)buf2;
}

//写一个函数打印数组
void print_arr(int arr[], int sz)
{
	int i = 0;
	for (i = 0; i < sz; i++)
	{
		printf("%d ", arr[i]);
	}
	printf("\n");
}

//结构体的排序：

struct Stu
{
	char name[20];
	int age;
};

//假设按照年龄来⽐较
int cmp_stu_by_age(const void* e1, const void* e2)
{
	return ((struct Stu*)e1)->age - ((struct Stu*)e2)->age;
}

//假设按照名字来⽐较
int cmp_stu_by_name(const void* e1, const void* e2)
{
	return strcmp(((struct Stu*)e1)->name, ((struct Stu*)e2)->name);
}


//按照年龄来排序
void test1()
{
	struct Stu s[] = { {"zhangsan", 20}, {"lisi", 30}, {"wangwu", 15} };
	int sz = sizeof(s) / sizeof(s[0]);
	bubble_sort(s, sz, sizeof(s[0]), cmp_stu_by_age);
	printf("按照年龄排序:\n");
	printf("%d %s\n", s[0].age, s[0].name);
}
//按照名字来排序
void test2()
{
	struct Stu s[] = { {"zhangsan", 20}, {"lisi", 30}, {"wangwu", 15} };
	int sz = sizeof(s) / sizeof(s[0]);
	bubble_sort(s, sz, sizeof(s[0]), cmp_stu_by_name);
	printf("按照名字排序:\n");
	printf("%d %s\n", s[0].age, s[0].name);
}

int main()
{
	int arr[] = { 2,3,5,6,8,7,9,1,4 };
	int num = sizeof(arr) / sizeof(arr[0]);
	int size = sizeof(arr[0]);
	bubble_sort(arr, num, size, cmp_int);
	print_arr(arr, num);

	test1();
	test2();
	return 0;
}